package recite.word.service.base.util.file;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class FileUtil {
    //MultipartFile转成file
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            System.out.println(file.getOriginalFilename());
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 转png格式
     *
     * @throws IOException
     */
    public static File toPng(MultipartFile file) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
        newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.white, null);
        int lastIndex = file.getOriginalFilename().lastIndexOf('.');
        String fileName = file.getOriginalFilename().substring(0, lastIndex) + ".png";
        File ans = new File(fileName);
        BufferedOutputStream outputStream = null;
        try {
            outputStream = cn.hutool.core.io.FileUtil.getOutputStream(ans);
            ImageIO.write(newBufferedImage, "png", outputStream);
        }finally {
            if (null != outputStream){
                outputStream.close();
            }
        }
        return ans;
    }
}
